JavaScript Let Keyword

    In the previous tutorial we learned about the JavaScript var keyword and how can we declare a variable using it. Before the introduction of ECMAScript 2015, JavaScript only supports var keyword for variable declaration but now it also supports two more new keywords let and const to declare a variable. In this tutorial, we will learn about the concept of let keyword in JavaScript.

    JavaScript let Keyword

    The let keyword is used to declare variables for block statements or expressions. The var keyword declares a variable for global or local(function) scope, but the let keyword declares a variable for block scope. A block statement or expression is the code that resides in the curly brackets {.....} . And the inside area of the curly brackets is known as block scope. Example

    <script>
        let name ="Rahul", id =20;
        if(id ==20)
        {
            let name ="Ravi";  //declare new variable
            console.log(name);  //Ravi
        }
        console.log(name); //Rahul
    </script>
    Output
    Ravi
    Rahul
    You can check the output in Console by inspecting the page. In the above output, you can see that the console.log(name) statement inside the if block print the name Ravi but the console.log(name) outside the if block print the name Rahul this is becaue, let variables can work with three scopes global, local, and block scope (new to JavaScript in ECMAScript 2015). The above if statement block {....} was a new block scope for let name="Ravi" statement. So instead of inheriting the already declared let name variable or redeclaring the name variable, it declared a new variable name with the value "Ravi" exclusive for the if statement. If we write the same above program with var keyword, then we would have a completely different output.
    <script>
        var name ="Rahul", id =20;
        if(id ==20)
        {
            var name ="Ravi";  //redeclare name variable
            console.log(name);  //Ravi 
        }
        console.log(name); //Ravi
    </script>
    Output
    Ravi
    Ravi
    As the var keyword does not follow the block scope it will treat the declaration of name variable inside the if statement as a redeclaration of the global variable name .

    Let block scope

    The variables that are defined inside a block scope using let keyword can not be accessed outside the block.
    <script>
        let name ="Rahul", id =20;
        if(id==20)
        {
            let age =17;  // declare new variable
            console.log(age);  //17 
        }
        console.log(age); //error
    </script>
    Output
    17
    Uncaught ReferenceError: age is not defined
    
    In the above example have declared the age variable inside the if statement block, so it is only available for that particular if block. And when we tried to print its value outside the if block it throws an error, because let variables are only available for their scope.

    let global, local, and block scope It's not like that we can only define let variable for block scope, we can also use the let variables as global, and local variables.

    <script>
        let global = 20; //declare global variable
    
        function func()
        {     
            let local = global+20; //declare local variable
            document.write("Local--> "+local);
            document.write("<br>")
        }
        func();
    
        if(true)
        {
            let block = global+20; //declare block variable
            document.write("Block-----> "+block)
            document.write("<br>")
        }
    
        document.write("Global-----> "+global)
    </script>
    Output
    Local--> 40
    Block-----> 40
    Global-----> 20

    Redeclaration of let variables

    Unlike the var keyword the let will throw a SyntaxError if we redeclare a variable in the same scope. Example

    <script>
        let global = 20;  //declare global variable
    
        let global = 40;  //error
    </script>

    let variable hoisting Like the var variables, let variables are also hoisted at the top of their respective scope or script when the JS engine compiles the code. But unlike var, they do not get initialized as undefined, which leads them to uninitialized variables. This means we can not access the let variable before their initialization or declaration. The let variables can not be read or write until they have been initialized. And initialization of a let variable can only happen during or after their declaration. that's why when we try to access the let variables before their declaration, we get the Uncaught ReferenceError: Cannot access 'variable' before initialization. This error-proof that the let variables are hoisted but not initialized.

    <script>
        console.log(p);
        let p;
    </script>

    Output

    Uncaught ReferenceError: Cannot access 'p' before initialization

    Where to use let variables?

    let variables are generally used for block-level code where we only want to use a variable for a specific block and that has no other use throughout the program. For example, we can use the let variable for for loop counters.

    <script>
        for(let i =0; i<10; i++)
        {
            console.log(i);
        }
        //i does not exist outside the for loop
    </script>

    In the above example, the i value will only be valid for the for loop block and once the for loop end the i gets destroyed.

    Summary

    • let keyword was introduced to JavaScript in ECMAScript2015.
    • let keyword define variables for local scope.
    • Redeclaration of let variables throws a Syntax error.
    • let variables get hoisted but not initialized at hoisting.

    People are also reading: